const regIntWithSign = /^[+-]{0,1}[0-9]+$/i;
const regIntWithoutSign = /^[0-9]+$/i;

function string2number(str) {
  let flag = 0;

  const tStr = str.trim();

  if (tStr.indexOf('e') !== -1) {
    flag += 1;
  }
  if (tStr.indexOf('E') !== -1) {
    flag += 2;
  }

  if (flag >= 3) {
    throw new Error('多个e/E');
  }

  let eSplit;
  if (flag !== 0) {
    eSplit = flag === 1 ? tStr.split('e') : tStr.split('E');
  } else {
    eSplit = [tStr];
  }

  let eCo;
  if (eSplit.length === 1) {
    eCo = 1;
  } else if (eSplit.length === 2) {
    if (regIntWithSign.test(eSplit[1])) {
      eCo = 10 ** eSplit[1];
    } else {
      throw new Error('指数非整数');
    }
  } else {
    throw new Error('指数错误');
  }

  const dotSplit = eSplit[0].split('.');
  let ret;
  if (dotSplit.length === 1) {
    // 整数
    if (regIntWithSign.test(dotSplit[0])) {
      ret = parseFloat(dotSplit[0]) * eCo;
    } else {
      throw new Error('整数部分非整数');
    }
  } else if (dotSplit.length === 2) {
    if (regIntWithSign.test(dotSplit[0]) === false) {
      throw new Error('整数部分非整数');
    } else if (regIntWithoutSign.test(dotSplit[1]) === false) {
      throw new Error('小数部分非小数');
    } else {
      ret = parseFloat(eSplit[0]) * eCo;
    }
  } else {
    throw new Error('多个小数点');
  }

  return ret;
}

export default {
  toNumber: string2number,
};
